package com.share.example.bcs.common.protocol.tcp;

import com.share.common.utils.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * java 中协议最好使用字符串----16进制忘记了
 */
@Slf4j
public class MsgBody {
    /**
     * 协议开头
     */
    private final static String protocol = "5050";

    /**
     * 消息体长度--6个字符串的长度
     */
    private int length;

    /**
     * 消息内容
     */
    private byte[] body;

    /*定义数据的位宽*/
    public final static int PROTOCOL_LEN = protocol.length();
    public final static int LENGTH_LEN = 6;

    public static String toPackage(byte[] body) {
        MsgBody msgBody = new MsgBody();
        msgBody.setBody(body);
        return msgBody.gen();
    }

    private String gen() {
        StringBuffer sb = new StringBuffer();
        sb.append(this.protocol);
        sb.append(StrUtil.intToStrAlign(this.length, LENGTH_LEN));
        if (this.body != null) {
            sb.append(new String(this.body));
        }
        return sb.toString();
    }

    public String getProtocol() {
        return protocol;
    }

    public int getLength() {
        return length;
    }

    public byte[] getBody() {
        return body;
    }

    public void setBody(byte[] body) {
        this.body = body;

        //把数据添加进去
        if (body != null) {
            this.length = body.length;
        } else {
            this.length = 0;
        }
    }
}
